package com.tech.thread.juc;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @Description:
 * @Author: zl
 * @Date: 2019/7/25 13:44
 */
public class SemaporeTest {
    private static final int THREAD_COUNT = 30;
    //1、创建固定大小的线程池
    private static ExecutorService threadPool = Executors.newFixedThreadPool(THREAD_COUNT);
    // Semaphore（int permits）接受一个整型的数字，表示可用的许可证数量。
    // Semaphore（10）表示允许10个线程获取许可证，也就是最大并发数是10
    private static Semaphore semaphore = new Semaphore(10);

    public static void main(String[] args) {
        for ( int i = 0; i < THREAD_COUNT; i++) {
            threadPool.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        //Semaphore的acquire()方法获取一个许可证，使用完之后调用release()方法归还许可证。
                        semaphore.acquire();
                        System.out.println("save data..........");
                        semaphore.release();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        threadPool.shutdown();
    }
}
